package com.utonw.carloan.activity.applyloan;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.utonw.carloan.R;
import com.utonw.carloan.activity.applyloan.view.StaticViewPager;
import com.utonw.carloan.activity.base.BaseActivity;
import com.utonw.carloan.adpter.applyloan.ApplyLoanAdapter;
import com.utonw.carloan.bean.NormalResponseBean;
import com.utonw.carloan.fragment.FragmentFactory;
import com.utonw.carloan.fragment.applyloan.LoanStepNineFragment;
import com.utonw.carloan.global.Constants;
import com.utonw.carloan.global.ReleaseData;
import com.utonw.carloan.net.NetCallBack;
import com.utonw.carloan.net.NetTool;
import com.utonw.carloan.utils.JsonUtils;
import com.utonw.carloan.utils.LogUtil;
import com.utonw.carloan.utils.UIUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by SEELE on 2017/3/21.
 */

/**
 * 提交资料界面，此界面内包含9个阶段的Fragment及 上一步 和 下一步 按钮
 */
public class LoanContentActivity extends BaseActivity {
    //下方8 Step ViewPager
    private StaticViewPager mLoanViewPager;
    //协调RadioGroup
    private HorizontalScrollView mScrollView;
    //记录当前RadioGroup的ID
    private int currentGroupId;
    //RadioGroup列表
    private RadioGroup mRadioGroup;

    //RadioButton列表
    private RadioButton mSelf, mHouse, mCar, mJob, mBank, mContract, mNet, mCommit;
    //校验位
    private int checkSum = 0;
    //RadioButton集合
    private ArrayList<RadioButton> radioButtonList;
    //前进按钮
    private TextView nextArrow;
    //后退按钮
    private TextView preArrow;
    //提交按钮
    private TextView commitBtn;
    //核心适配器
    private ApplyLoanAdapter mLoanAdapter;


    @Override
    public int setLayout() {
        return R.layout.activity_applyloan_content;
    }

    @Override
    public void initView() {
        mLoanViewPager = (StaticViewPager) findViewById(R.id.vp_loan);
        mScrollView = (HorizontalScrollView) findViewById(R.id.hs_title_guide);
        mRadioGroup = (RadioGroup) findViewById(R.id.rg_title_guide);
        //绑定方向按钮
        nextArrow = (TextView) findViewById(R.id.tv_btn_next_step);
        preArrow = (TextView) findViewById(R.id.tv_btn_pre_step);
        //绑定提交按钮
        commitBtn = (TextView) findViewById(R.id.tv_btn_commit_step);
        //绑定RadioButton列表
        mSelf = (RadioButton) findViewById(R.id.rb_item_self);
        mHouse = (RadioButton) findViewById(R.id.rb_item_house);
        mCar = (RadioButton) findViewById(R.id.rb_item_car);
        mJob = (RadioButton) findViewById(R.id.rb_item_job);
        mBank = (RadioButton) findViewById(R.id.rb_item_bank);
        mContract = (RadioButton) findViewById(R.id.rb_item_contract);
        mNet = (RadioButton) findViewById(R.id.rb_item_net);
        mCommit = (RadioButton) findViewById(R.id.rb_item_commit);

    }

    @Override
    public void initData() {

        //初始化ViewPager
        initViewPager();

        //初始化指向按钮
        initArrowButton();

        //初始化ScrollView
        initScrollView();
    }

    private void initArrowButton() {

        //前进，后退，保存按钮监听
        preArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //校验所有View
                if (mLoanAdapter.getCurrentFragment().checkEmpty()) {
                    setCheckSum(17);
                } else {
                    setCheckSum(17);
                    // TODO: 2017/4/6
                }
            }
        });
        nextArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //校验所有View
                if (mLoanAdapter.getCurrentFragment().checkEmpty()) {
                    setCheckSum(66);
                } else {
                    setCheckSum(66);
                    // TODO: 2017/4/6
                }


            }
        });

        //初始化隐藏向前按钮
        preArrow.setVisibility(View.GONE);
        //初始化隐藏提交按钮
        commitBtn.setVisibility(View.GONE);


        //提交按钮监听
        commitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2017/3/31 提交所有表单字段
                final Map<String, Object> tempCommit = new HashMap<>();
                //获取全部Entry界面的TextView
                for (int i = 0; i < ReleaseData.getAllTextViewEntry.size(); i++) {
                    tempCommit.put((String) ReleaseData.getAllTextViewEntry.get(i).getTag(),
                            ReleaseData.getAllTextViewEntry.get(i).getText().toString().
                                    equals(getString(R.string.apply_page_begin_please_choose))
                                    ? null : ReleaseData.getAllTextViewEntry.get(i).getText().toString());
                }
                //获取全部Content界面的TextView
                for (int i = 0; i < ReleaseData.getAllTextViewContent.size(); i++) {
                    tempCommit.put((String) ReleaseData.getAllTextViewContent.get(i).getTag(),
                            ReleaseData.getAllTextViewContent.get(i).getText().toString().
                                    equals(getString(R.string.apply_page_begin_please_choose))
                                    ? null : ReleaseData.getAllTextViewContent.get(i).getText().toString());
                }
                //获取全部Entry界面的EditText
                for (int i = 0; i < ReleaseData.getAllEditTextEntry.size(); i++) {
                    tempCommit.put((String) ReleaseData.getAllEditTextEntry.get(i).getTag(),
                            ReleaseData.getAllEditTextEntry.get(i).getText().toString().
                                    equals("") ? null : ReleaseData.getAllEditTextEntry.get(i).getText().toString());
                }
                //获取全部Content界面的EditText
                for (int i = 0; i < ReleaseData.getAllEditTextContent.size(); i++) {
                    tempCommit.put((String) ReleaseData.getAllEditTextContent.get(i).getTag(),
                            ReleaseData.getAllEditTextContent.get(i).getText().toString().
                                    equals("") ? null : ReleaseData.getAllEditTextContent.get(i).getText().toString());
                }
                //添加所有联系人集合
                tempCommit.put("contactList", mLoanAdapter.getAllContract().getFinalData());

                //添加所有Entry界面的Switch状态
                for (int i = 0; i < ReleaseData.getAllSwitchEntry.size(); i++) {
                    tempCommit.put((String) ReleaseData.getAllSwitchEntry.get(i).getTag(),
                            ReleaseData.getAllSwitchEntry.get(i).isChecked() ? 1 + "" : 0 + "");
                }

                //添加所有Content界面的Switch状态
                for (int i = 0; i < ReleaseData.getAllSwitchContent.size(); i++) {
                    tempCommit.put((String) ReleaseData.getAllSwitchContent.get(i).getTag(),
                            ReleaseData.getAllSwitchContent.get(i).isChecked() ? 1 + "" : 0 + "");
                }

                //Entry界面添加 单选按钮
                for (int i = 0; i < ReleaseData.getAllRadioGroupEntry.size(); i++) {
                    tempCommit.put((String) ReleaseData.getAllRadioGroupEntry.get(i).getTag(),
                            ReleaseData.getAllRadioGroupEntry.get(i).getCheckedRadioButtonId() == R.id.rbtn_male ? "M" : "FM");
                }

                //Content界面添加 单选按钮
                for (int i = 0; i < ReleaseData.getAllRadioGroupContent.size(); i++) {
                    tempCommit.put((String) ReleaseData.getAllRadioGroupContent.get(i).getTag(),
                            ReleaseData.getAllRadioGroupContent.get(i).getCheckedRadioButtonId() == R.id.rbtn_male ? "M" : "FM");
                }
                //获取全部上传的图片
                HashMap tempUploadImages = new HashMap();
                ArrayList<HashMap> tempUploadImageList = new ArrayList<>();
                for (int i = 0; i < ReleaseData.getAllImageUpload.size(); i++) {
                    HashMap<Object, Object> tempMap = (HashMap<Object, Object>) ReleaseData.getAllImageUpload.get(i).getTag();
                    tempUploadImages.put(tempMap.get("paramName"), tempMap.get("base64"));
                }
                tempUploadImageList.add(tempUploadImages);
                //添加所有图片集合
                tempCommit.put("carImageList", tempUploadImageList);

                //检测是否有信用卡,单独处理
                if (!mLoanAdapter.hasCreditCard().hasCreditCard()) {
                    tempCommit.remove("creditCard");
                    tempCommit.put("creditCard", null);
                    tempCommit.remove("creditCardBankName");
                    tempCommit.put("creditCardBankName", null);
                }


                LogUtil.d(JsonUtils.toJsonByJackson(tempCommit));


                NetTool.getInstance().startRequest(LoanContentActivity.this, true, Constants.LOANCOMMIT, tempCommit, NormalResponseBean.class, new NetCallBack<NormalResponseBean>() {
                    @Override
                    public void onSuccess(NormalResponseBean response) {
                        if (response.getRetCode().equals("000000")) {
                            tempCommit.clear();
                            Intent intent=new Intent(Constants.LOAN_COMMIT_RECEIVER);
                            sendBroadcast(intent);
                            finish();
                            UIUtils.showShortToast(response.getMessage());
                        } else {
                            UIUtils.showShortToast(response.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                });

            }
        });
    }

    //校验RadioButton集合的CheckSum
    private void setCheckSum(int arrowId) {

        switch (arrowId) {
            //next
            case 66:
                ++checkSum;
                radioButtonList.get(checkSum).setChecked(true);
                break;
            //pre
            case 17:
                --checkSum;
                radioButtonList.get(checkSum).setChecked(true);
                break;
        }


    }

    private void initViewPager() {
        //9步流程适配器
        mLoanAdapter = new ApplyLoanAdapter(getSupportFragmentManager());
        ArrayList<Fragment> data = new ArrayList<>();

        //测试用数据：9份fragment
        data.add(FragmentFactory.createLoanFragment(0));
        data.add(FragmentFactory.createLoanFragment(2));
        data.add(FragmentFactory.createLoanFragment(3));
        data.add(FragmentFactory.createLoanFragment(4));
        data.add(FragmentFactory.createLoanFragment(5));
        data.add(FragmentFactory.createLoanFragment(6));
        data.add(FragmentFactory.createLoanFragment(7));
        data.add(FragmentFactory.createLoanFragment(8));

        mLoanAdapter.setData(data);
        mLoanViewPager.setOffscreenPageLimit(10);
        mLoanViewPager.setAdapter(mLoanAdapter);
        mLoanViewPager.setScrollble(false);
        mLoanViewPager.setCurrentItem(0);


        //ViewPager滑动监听
        mLoanViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                switch (position) {
                    case 0:
                        commitBtn.setVisibility(View.GONE);
                        nextArrow.setVisibility(View.VISIBLE);
                        preArrow.setVisibility(View.GONE);
                        // mRadioGroup.check(R.id.rb_item_self);
                        break;

                    case 1:
                        commitBtn.setVisibility(View.GONE);
                        nextArrow.setVisibility(View.VISIBLE);
                        preArrow.setVisibility(View.VISIBLE);
                        // mRadioGroup.check(R.id.rb_item_house);
                        break;

                    case 2:
                        commitBtn.setVisibility(View.GONE);
                        nextArrow.setVisibility(View.VISIBLE);
                        preArrow.setVisibility(View.VISIBLE);
                        // mRadioGroup.check(R.id.rb_item_car);
                        break;

                    case 3:
                        commitBtn.setVisibility(View.GONE);
                        nextArrow.setVisibility(View.VISIBLE);
                        preArrow.setVisibility(View.VISIBLE);
                        //  mRadioGroup.check(R.id.rb_item_job);
                        break;

                    case 4:
                        commitBtn.setVisibility(View.GONE);
                        nextArrow.setVisibility(View.VISIBLE);
                        preArrow.setVisibility(View.VISIBLE);
                        //  mRadioGroup.check(R.id.rb_item_bank);
                        break;

                    case 5:
                        commitBtn.setVisibility(View.GONE);
                        nextArrow.setVisibility(View.VISIBLE);
                        preArrow.setVisibility(View.VISIBLE);
                        // mRadioGroup.check(R.id.rb_item_contract);
                        break;

                    case 6:
                        commitBtn.setVisibility(View.GONE);
                        nextArrow.setVisibility(View.VISIBLE);
                        preArrow.setVisibility(View.VISIBLE);
                        //  mRadioGroup.check(R.id.rb_item_net);
                        break;

                    case 7:
                        LoanStepNineFragment tempFra = (LoanStepNineFragment) mLoanAdapter.getCurrentFragment();
                        tempFra.setAllText();
                        commitBtn.setVisibility(View.VISIBLE);
                        nextArrow.setVisibility(View.GONE);
                        preArrow.setVisibility(View.VISIBLE);
                        // mRadioGroup.check(R.id.rb_item_commit);
                        break;


                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    //设置协调RadioButton选中位置
    private void coordinateRadioButton(RadioButton mSelf) {
        WindowManager wm = this.getWindowManager();
        final int width = wm.getDefaultDisplay().getWidth() / 2;
        int scrollX = mScrollView.getScrollX();
        int left = mSelf.getLeft();
        int leftScreen = left - scrollX;
        mScrollView.smoothScrollBy((leftScreen - width + (mSelf.getWidth() / 2)), 0);
    }

    private void initScrollView() {
        //设置默认GroupId，当前是第一页
        currentGroupId = R.id.rb_item_self;
        //RaidoGroup点击事件
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (null != mLoanAdapter.getCurrentFragment()) {
                    if (mLoanAdapter.getCurrentFragment().checkEmpty()||true) {

                        RadioButton rb = (RadioButton) findViewById(checkedId);

                        coordinateRadioButton(rb);

                        switch (checkedId) {
                            case R.id.rb_item_self:
                                mLoanViewPager.setCurrentItem(0, true);
                                currentGroupId = checkedId;
                                checkSum = 0;
                                break;

                            case R.id.rb_item_house:
                                mLoanViewPager.setCurrentItem(1, true);
                                currentGroupId = checkedId;
                                checkSum = 1;
                                break;

                            case R.id.rb_item_car:
                                mLoanViewPager.setCurrentItem(2, true);
                                currentGroupId = checkedId;
                                checkSum = 2;
                                break;

                            case R.id.rb_item_job:
                                mLoanViewPager.setCurrentItem(3, true);
                                currentGroupId = checkedId;
                                checkSum = 3;
                                break;

                            case R.id.rb_item_bank:
                                mLoanViewPager.setCurrentItem(4, true);
                                currentGroupId = checkedId;
                                checkSum = 4;
                                break;

                            case R.id.rb_item_contract:
                                mLoanViewPager.setCurrentItem(5, true);
                                currentGroupId = checkedId;
                                checkSum = 5;
                                break;

                            case R.id.rb_item_net:
                                mLoanViewPager.setCurrentItem(6, true);
                                currentGroupId = checkedId;
                                checkSum = 6;
                                break;

                            case R.id.rb_item_commit:
                                mLoanViewPager.setCurrentItem(7, true);
                                currentGroupId = checkedId;
                                checkSum = 7;
                                break;


                        }

                    } else {

                        UIUtils.showShortToast(getString(R.string.must_input));
                        mRadioGroup.check(currentGroupId);

                    }
                }

                //关闭RadioGroup点击
                disableRadioGroup();
            }
        });
        //默认选中第一个
        mRadioGroup.check(R.id.rb_item_self);

        //初始化RadioButton集合
        radioButtonList = new ArrayList<>();
        radioButtonList.add(mSelf);
        radioButtonList.add(mHouse);
        radioButtonList.add(mCar);
        radioButtonList.add(mJob);
        radioButtonList.add(mBank);
        radioButtonList.add(mContract);
        radioButtonList.add(mNet);
        radioButtonList.add(mCommit);
    }

    @Override
    public String setTitle() {
        return getString(R.string.apply_data);
    }


    @Override
    protected void onDestroy() {
        ReleaseData.getAllTextViewContent.clear();
        ReleaseData.getAllEditTextContent.clear();
        ReleaseData.getAllContractBean.clear();
        ReleaseData.getAllSwitchContent.clear();
        ReleaseData.getAllRadioGroupContent.clear();

        ReleaseData.getAllResultContent.clear();
        ReleaseData.tempUnused.clear();
        FragmentFactory.destroy();
        super.onDestroy();
    }


    //关闭上方选择条
    public void disableRadioGroup() {
        for (int i = 0; i < mRadioGroup.getChildCount(); i++) {
            mRadioGroup.getChildAt(i).setEnabled(false);
        }
    }

    //启动上方选择条
    public void enableRadioGroup() {
        for (int i = 0; i < mRadioGroup.getChildCount(); i++) {
            mRadioGroup.getChildAt(i).setEnabled(true);
        }
    }
}
